<?php
/**
 * 商家账户类
 *
 */
class User_Merchant_Account_Money 
{
	const _CONST_MERCHANT_ACCOUNT_TB = 'merchant_account';
	
	private $_merchant_uid, $_shop_id;
	public function __construct($merchant_uid)
	{
		$obj_shop  = new Model_Shopinfo();
		$this->_merchant_uid = (int) $merchant_uid;
		$shop_info			 = $obj_shop->get_shopinfo_byuid($this->_merchant_uid);
		$this->_shop_id		 = empty($shop_info) ? 0 : $shop_info[0]['id'];
	}

	/**
	 * 获得商家各种类型钱的描述信息
	 *
	 * @param int $merchant_uid
	 * @param String $money_type Kohana::config('account.money_type')
	 *
	 * @return array(
	 *			array(
	 *				'shop_id'
	 *				'merchant_uid'
	 *				'money'			=> int //单位：分
	 *				'type'			=> int //钱的类型   Kohana::config('account.money_type.***')
	 *				'start_time'	=> int 
	 *				'end_time'		=> int
	 *				'status'		=> int // 合同状态 Kohana::config('account.contract_status') 
	 *				'flag'			=> int // 付款状态 Kohana::config('account.pay_status')
	 *				'invoice_time'	=> int //发票日期
	 *				'receipt_time'  => int //收据日期
	 *				'create_time'	=> int
	 *				'update_time'	=> int
	 *			),
	 *			...
	 *			)
	 */
	public function get_money_info($merchant_uid, $money_type, $start = null, $end = null)
	{
		$type = Kohana::config('account.money_type.'.$money_type);
		
		$query = DB::select()
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('merchant_uid', '=', $merchant_uid)
					->where('type', '=', $type);
		if(!empty($start))
			$query->where('start_time', '>=', $start);
		if(!empty($end))
			$query->where('end_time','<=', $end);

		$data = $query->execute()
					  ->as_array();
		
		for($i=0; $i< count($data); $i++)
		{
			$data[$i]['start_time'] = date('Y-m-d', $data[$i]['start_time']);
			$data[$i]['end_time']	= date('Y-m-d', $data[$i]['end_time']);
			$data[$i]['invoice_time'] = date('Y-m-d', $data[$i]['invoice_time']);
			$data[$i]['receipt_time'] = date('Y-m-d', $data[$i]['receipt_time']);
			$data[$i]['money']		= $data[$i]['money']/100;
		}
		return $data;
	}

	/**
	 * 以年查询以月为组获取充值记录
	 *
	 * @param int $year 年
	 *
	 * @return array(
	 *	'sum' => 199,
	 *	'list' => array(
	 *		array(
	 *         'annual_fee'        => 9,
	 *         'technical_service' => 12.1,
	 *         'margin'            => 2,
	 *         'stored_service'    => 11.23,
	 *      ),
	 *  ),
	 *  ....
	 *),
	 *
	 * );
	 */
	public function get_money_list($year)
	{
		$expry  = DB::expr('from_unixtime(create_time,"%Y")');
		$exprm  = DB::expr('from_unixtime(create_time,"%Y-%m")');
		$list   = array();
		$query  = DB::select(array($exprm,'m'), 'type', array('sum("money")','money'))
			-> from(self::_CONST_MERCHANT_ACCOUNT_TB)
			-> where ($expry,'=',$year)
			-> group_by ('type')
			-> group_by ('m')
			-> order_by ('m','desc')
			-> execute ()
			-> as_array();

		if(!empty($query))
		{
			$sum['annual_fee']        = 0;
			$sum['technical_service'] = 0;
			$sum['margin']            = 0;
			$sum['stored_service']    = 0;
			foreach($query as $li)
			{
				$t_money              = empty($li['money']) ? 0 : ($li['money'] / 100);
				if($li['type'] == Kohana::config('account.money_type.annual_fee'))
				{
					$list[$li['m']]['annual_fee']           = $t_money;
					$sum['annual_fee']                     += $t_money;
				}
				elseif($li['type'] == Kohana::config('account.money_type.technical_service'))
				{
					$list[$li['m']]['technical_service']    = $t_money;
					$sum['technical_service']              += $t_money;
				}
				elseif($li['type'] == Kohana::config('account.money_type.margin'))
				{
					$list[$li['m']]['margin']               = $t_money;
					$sum['margin']                         += $t_money;
				}
				elseif($li['type'] == Kohana::config('account.money_type.stored_service'))
				{
					$list[$li['m']]['stored_service']       = $t_money;
					$sum['stored_service']                 += $t_money;
				}
				else
				{
					continue;
				}

			}
		}
		$re_list['list'] = $list;
		$re_list['sum']  = $sum;
		return $re_list;
	}

	/**
	 * 以某时间段，获取充值列表详细记录
	 *
	 * @param int $start_time  开始时间戳
	 * @param int $end_time 结束时间戳
	 * @param $merchant_uids 一组商家
	 * @param $type 充值的类型 类型所见account配置文件
	 * @param $is_invoice 是否已开票据
	 *
	 * @return array(
	 *   array(
	 *     'typename'      => '服务费',//费用说明
	 *     'id' => 12, //记录id
	 *     'type' => 1, //类型id
	 *     'date' => '2011-01-01', //产生时间
	 *     'money' => 100.00,
	 *     'shop_name' => '测试商铺', //店铺名称
	 *     'operater_man' => 'admin', //操作人名
	 *     'operate_desc' => '运营备注',
	 *     'desc' => '普通备注',
	 *     'invoice_status' => 1, //是否已开票
	 *     'start_time' => 'Y-m-d', //有有效期的开始日期格式
	 *     'end_time' => 'Y-m-d', //有有效期的结束日期格式
	 *     'invoice_time' => 'Y-m-d', //开票日期
	 *     'create_time' => 'Y-m-d', //创建日期
	 *   ),
	 * );
	 *
	 */
	public function get_money_list_detail($start_time, $end_time, $merchant_uids = array(), $type = '', $is_invoice = -1)
	{
		$list   = array();
		$query = DB::select("*")
			-> from(self::_CONST_MERCHANT_ACCOUNT_TB)
			-> where ('create_time','>=',$start_time)
			-> where ('create_time','<=',$end_time);

		if(!empty($merchant_uids))
			$query = $query -> where ('merchant_uid', 'in', $merchant_uids);

		if(!empty($type))
			$query = $query -> where ('type', '=', Kohana::config('account.money_type.'.$type));

		if($is_invoice != -1 && $type != 'stored_service')
		{
			$query = $query -> where ('invoice_status', '=', $is_invoice)
				-> where ('type', '!=', Kohana::config('account.money_type.stored_service'));
		}
		
		$query = $query -> order_by ('create_time','desc')
			-> execute ()
			-> as_array();

		if(!empty($query))
		{
			foreach($query as $li)
			{
				$merchant_uid           = $li['merchant_uid'];
				$shop_infos             = Shop_Info::merchant_shops($merchant_uid);
				if(!empty($shop_infos))
					$shop_info          = isset($shop_infos[0]) ? $shop_infos[0] : array();

				if($li['type'] == Kohana::config('account.money_type.annual_fee'))
					$v['typename']      = Kohana::config('account.money_type_name.annual_fee');
				elseif($li['type'] == Kohana::config('account.money_type.margin'))
					$v['typename']      = Kohana::config('account.money_type_name.margin');
				elseif($li['type'] == Kohana::config('account.money_type.stored_service'))
					$v['typename']      = Kohana::config('account.money_type_name.stored_service');
				else
					$v['typename']      = '';

				$v['id']                = $li['id'];
				$v['type']              = $li['type'];
				$v['date']              = empty($li['create_time']) ? '-' : date('Y-m-d',$li['create_time']);
				$v['money']             = empty($li['money']) ? 0 : $li['money'] / 100;
				$v['shop_name']         = isset($shop_info['shop_name']) ? $shop_info['shop_name'] : '';
				$v['operater_man']      = $li['operater_man'];
				$v['operate_desc']      = $li['operate_desc'];
				$v['desc']              = $li['desc'];
				$v['invoice_status']    = $li['invoice_status'];
				$v['start_time']        = empty($li['start_time']) ? '-' : date('Y-m-d',$li['start_time']);
				$v['end_time']          = empty($li['end_time']) ? '-' : date('Y-m-d',$li['end_time']);
				$v['invoice_time']      = empty($li['invoice_time']) ? '-' : date('Y-m-d',$li['invoice_time']);
				$v['receipt_time']      = empty($li['receipt_time']) ? '-' : date('Y-m-d',$li['receipt_time']);
				$v['create_time']       = empty($li['create_time']) ? '-' : date('Y-m-d',$li['create_time']);
				$v['shop_id']           = isset($shop_info['id']) ? $shop_info['id'] : 0;
				$v['contract_id']       = $li['contract_id'];
				$list[]                 = $v;
			}
		}

		return $list;
	}

	/**
	 * 获得某条充值记录信息
	 *
	 * @param int $id
	 * 
	 * @return $data = array(
	 *				'shop_id'		=> int //店铺id 
	 *				'merchant_uid'  => int //商家uid
	 *				'start_time'    => int //开始时间
	 *				'end_time'		=> int //结束时间
	 *				'type'			=> int //钱的类型 Kohana::config('account.money_type.***')
	 *				'money'			=> int //单位： 分
	 *				'invoice_time'  => int //发票时间
	 *				'receipt_time'  => int //收据时间
	 *				'operater_man'  => String //收款人
	 *				'create_time'	=> int //创建时间
	 *				'desc'			=> String //描述
	 *				);
	 */
	public function get_info($id)
	{
		$id   = (int) $id;
		if($id <= 0)
			return array();

		$data = DB::select()
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('id', '=', $id)
					->execute()
					->as_array();
		return empty($data) ? array() : $data[0];
	}

	/**
	 * 判断某个合同的充值数据
	 *
	 *	@param int $contract_id
	 *
	 *  @return int $data (0: 未付款， 3：全部付款 其他：部分付款) 
	 */
	public function is_haved($contract_id)
	{
		$contract_id   = (int) $contract_id;
		if($contract_id <= 0)
			return false;

		$data = DB::select(array('distinct("type")','type'))
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('contract_id', '=', $contract_id)
					->execute()
					->as_array();
		
		return count($data);
	}

	/**
	 * 判断某个合同的是否有保证金充值
	 *
	 *	@param int $contract_id
	 *
	 *  @return boolean 
	 */
	public function is_haved_margin($contract_id)
	{
		$contract_id   = (int) $contract_id;
		if($contract_id <= 0)
			return false;

		$data = DB::select(array('distinct("type")','type'))
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('contract_id', '=', $contract_id)
					->where('type', '=', Kohana::config('account.money_type.margin'))
					->execute()
					->as_array();

		return count($data) > 0 ? TRUE : FALSE;

	}

	/**
	 * 判断某合同是已收入服务费
	 *
	 * @param int $contract_id
	 *
	 * @return boolean
	 */
	public function is_haved_stored_service($contract_id)
	{
		$contract_id   = (int) $contract_id;
		if($contract_id <= 0)
			return false;

		$data = DB::select(array('count("id")','c'))
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('contract_id', '=', $contract_id)
					->where('type', '=', Kohana::config('account.money_type.stored_service'))
					->execute()
					->get("c");
		
		return $data > 0 ? TRUE : FALSE;
	}

	/**
	 * 判断某合同是否已收入年费
	 *
	 * @param int $contract_id
	 *
	 * @raturn boolean
	 */
	public function is_haved_annual_fee($contract_id)
	{
		$contract_id   = (int) $contract_id;
		if($contract_id <= 0)
			return false;

		$data = DB::select(array('count("id")','c'))
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('contract_id', '=', $contract_id)
					->where('type', '=', Kohana::config('account.money_type.annual_fee'))
					->execute()
					->get("c");
		
		return $data > 0 ? TRUE : FALSE;

	}

	/**
	 * 判断某个商户某段时间内是否充值
	 *
	 *	@param int $uid
	 *	@param int $start_time
	 *	@param int $end
	 *
	 *	@return boolean
	 *
	 */
	public function has_info($uid, $start, $end)
	{
		$uid   = (int) $uid;
		if($uid <= 0)
			return false;

		$data = DB::select()
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('merchant_uid', '=', $uid)
					->where('start_time', '=', $start)
					->where('end_time', '=', $end)
					->execute();
		
		return $data->valid();
	}

	/**
	 * 更新某条充值记录信息
	 *	@param int $id
	 *  @param $data = array(
	 *				'shop_id'		=> int //店铺id 
	 *				'merchant_uid'  => int //商家uid
	 *				'start_time'    => int //开始时间
	 *				'end_time'		=> int //结束时间
	 *				'type'			=> int //钱的类型 Kohana::config('account.money_type.***')
	 *				'money'			=> int //单位： 分
	 *				'invoice_time'  => int //发票时间
	 *				'receipt_time'  => int //收据时间
	 *				'operater_man'  => String //收款人
	 *				'create_time'	=> int //创建时间
	 *				'desc'			=> String //描述
	 *				);
	 *
	 *	@return boolean
	 */
	public function set_info($id, $data)
	{
		$desc = "";
		$id   = (int) $id;
		if($id <= 0)
			return FALSE;

		$info = $this->get_info($id);
		if(empty($info))
			return FALSE;

		unset($data['id']);
		
		foreach($data as $k => $c)
		{
			if($info[$k] != $c)
				$desc .= '['.$k.'] 由：'.$info[$k].'改为：'.$c.'，';
		}

		$data['update_time'] = DB::expr('unix_timestamp(now())');
		$rs = DB::update(self::_CONST_MERCHANT_ACCOUNT_TB)
				->set($data)
				->where('id', '=', $id)
				->execute();

		if($rs)
		{
			Bill_Log_Charge::update_charge($id,$desc);
			return TRUE;
		}
		else
			return FALSE;
	}

	/**
	 * 获得商家账户目前金额
	 * @param int $merchant_uid //如果不传， 默认当前商家的uid 
	 *
	 * @return array(
	 *				'annual_fee'		=> int //年费 单位： 分  
	 *				'techical_service'	=> int //技术服务费 （暂时不用）单位： 分 
	 *				'margin'			=> int //保证金 单位：分 
	 *				'stored_service'	=> int //预缴服务费 单位：分 
	 *				)
	 */
	public function get_money($merchant_uid = NULL)
	{
		$operate_type = Kohana::config('account.operate_type');
	
		if(!empty($merchant_uid))
			$uid	= $merchant_uid;
		else
			$uid	= $this->_merchant_uid;

		$recharge = DB::select(array('sum("money")', 'money'))
					->select('type')
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('merchant_uid', '=', $uid)
					->where('operate_type', '=', $operate_type['recharge'])
					->group_by('type')
					->execute()
					->as_array();

		$charge = DB::select(array('sum("money")', 'money'))
					->select('type')
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('merchant_uid', '=', $uid)
					->where('operate_type', '=', $operate_type['charge'])
					->execute()
					->as_array();

		$charge_money = empty($charge) ? 0 : $charge[0]['money'];
		
		$rs_data = array();
		for($i=0; $i< count($recharge); $i++)
		{
			switch($recharge[$i]['type'])
			{
				case Kohana::config('account.money_type.annual_fee') :
					$rs_data['annual_fee'] = $recharge[$i]['money'];
					break;
				case Kohana::config('account.money_type.technical_service') :
					$rs_data['technical_service'] = $recharge[$i]['money'];
					break;
				case Kohana::config('account.money_type.margin') :
					$rs_data['margin'] = $recharge[$i]['money'];
					break;
				case Kohana::config('account.money_type.stored_service') :
					$rs_data['stored_service'] = $recharge[$i]['money'] -  $charge_money;
					break;
			}
		}
		return $rs_data;
	}

	/**
	 * 录入商家账户金额
	 *
	 * @param int $operate_type 
	 *			  // 录入还是扣款 (目前只要录入) Kohana::config('account.operate_type.***');
	 * @param int $money_type  
	 *            // 钱的类型（年费、保证金、预缴服务费等） Kohana::config('account.money_type.***');
	 * @param int $money    // 单位： 分
	 * @param int String $desc     // 描述信息
	 * @param array $others = array(
	 *							'start_time' => int //开始时间
	 *							'end_time'   => int //结束时间
	 *							'invoice'	 => int //开发票的时间
	 *							'receipt'    => int //收据时间
	 *							'operate_desc' => String //运营描述 只要运营同学可见， 商家不可见
	 *							'operater_man' => String //操作人
	 *							'desc'		 => String // 描述 商家可见
	 *				)
	 *
	 * @return boolean
	 */
	public function set_money($operate_type, $money_type, $money, $others = array())
	{
		if($this->_merchant_uid <= 0)
			return FALSE;
		$data	= array(
						'shop_id'	   => $this->_shop_id,
						'merchant_uid' => $this->_merchant_uid,
						'operate_type' => $operate_type,
						'type'		   => $money_type,
						'money'        => $money,
						'status'	   => $others['status'],
						'start_time'   => $others['start_time'],
						'end_time'	   => $others['end_time'],
						'invoice_time' => $others['invoice'],
						'invoice_status' => $others['invoice_status'],
						'receipt_time' => $others['receipt'],
						'operate_desc' => $others['operate_desc'],
						'operater_man' => $others['operater_man'],
						'desc'	       => $others['desc'],
						'contract_id'  => $others['contract_id'],
						'create_time'  => DB::expr('unix_timestamp(now())'),
						'update_time'  => DB::expr('unix_timestamp(now())'),
					);
/*
		$rs	 = DB::select()
					->from(self::_CONST_MERCHANT_ACCOUNT_TB)
					->where('merchant_uid', '=', $this->_merchant_uid)
					->where('type', '=', $money_type)
					->where('operate_type', '=', $operate_type)
					->where('money', '=', $money)
					->execute();

		if($rs->valid())
			return TRUE;
*/
		list($insert_id, $rows) = DB::insert(self::_CONST_MERCHANT_ACCOUNT_TB)
									->columns(array_keys($data))
									->values(array_values($data))
									->execute();
		

		if($insert_id)
		{
			Bill_Log_Charge::insert_charge($insert_id);
			return TRUE;
		}
		else
			return FALSE;
	}
}
?>
